package com.feihe.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feihe.util.AESUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class EncryptionService {
    
    @Value("${app.aes.key}")
    private String aesKey;
    
    @Value("${app.aes.enabled:true}")
    private boolean aesEnabled;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 处理可能加密的请求体
     * @param requestBody 原始请求体
     * @return 解密后的JSON字符串
     */
    public String decryptRequestIfNeeded(Map<String, Object> requestBody) {
        if (!aesEnabled) {
            try {
                return objectMapper.writeValueAsString(requestBody);
            } catch (Exception e) {
                throw new RuntimeException("JSON序列化失败", e);
            }
        }
        
        // 检查是否包含加密字段
        if (requestBody.containsKey("encrypted")) {
            String encryptedData = (String) requestBody.get("encrypted");
            if (encryptedData != null && !encryptedData.isEmpty()) {
                try {
                    // 解密数据
                    return AESUtil.decrypt(encryptedData, aesKey);
                } catch (Exception e) {
                    throw new RuntimeException("请求解密失败: " + e.getMessage(), e);
                }
            }
        }
        
        // 如果不是加密请求，直接返回JSON字符串
        try {
            return objectMapper.writeValueAsString(requestBody);
        } catch (Exception e) {
            throw new RuntimeException("JSON序列化失败", e);
        }
    }

    public String decryptRequestIfNeededCreateReservation(Map<String, Object> requestBody) {
//        if (!aesEnabled) {
//            try {
//                System.out.println("================");
//                return objectMapper.writeValueAsString(requestBody);
//            } catch (Exception e) {
//                throw new RuntimeException("JSON序列化失败", e);
//            }
//        }

        // 检查是否包含加密字段
        //if (requestBody.containsKey("encrypted")) {
            String encryptedData = (String) requestBody.get("encrypted");
            if (encryptedData != null && !encryptedData.isEmpty()) {
                try {
                    System.out.println("----------------");
                    // 解密数据
                    return AESUtil.decrypt(encryptedData, aesKey);
                } catch (Exception e) {
                    throw new RuntimeException("请求解密失败: " + e.getMessage(), e);
                }
            }else{
                throw new RuntimeException("请求解密失败: empty");
            }
        //}

        // 如果不是加密请求，直接返回JSON字符串
//        try {
//            System.out.println("****************");
//            return objectMapper.writeValueAsString(requestBody);
//        } catch (Exception e) {
//            throw new RuntimeException("JSON序列化失败", e);
//        }
    }
    
    /**
     * 将JSON字符串转换为指定类型的对象
     */
    public <T> T parseDecryptedData(String jsonData, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonData, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 从解密的JSON中提取指定字段
     */
    public Object extractField(String jsonData, String fieldName) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonData);
            JsonNode fieldNode = jsonNode.get(fieldName);
            if (fieldNode == null) {
                return null;
            }
            
            if (fieldNode.isTextual()) {
                return fieldNode.asText();
            } else if (fieldNode.isInt()) {
                return fieldNode.asInt();
            } else if (fieldNode.isLong()) {
                return fieldNode.asLong();
            } else if (fieldNode.isBoolean()) {
                return fieldNode.asBoolean();
            } else {
                return fieldNode.toString();
            }
        } catch (Exception e) {
            throw new RuntimeException("字段提取失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 检查请求是否被加密
     */
    public boolean isEncryptedRequest(Map<String, Object> requestBody) {
        return aesEnabled && requestBody.containsKey("encrypted");
    }
    
    /**
     * 加密响应数据（可选功能）
     */
    public String encryptResponse(Object responseData) {
        if (!aesEnabled) {
            return null;
        }
        
        try {
            String jsonData = objectMapper.writeValueAsString(responseData);
            return AESUtil.encrypt(jsonData, aesKey);
        } catch (Exception e) {
            throw new RuntimeException("响应加密失败: " + e.getMessage(), e);
        }
    }
} 